package com.whiteape.book.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;


import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.whiteape.book.R;
import com.whiteape.book.contract.SearchContract;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.model.bo.SearchResultBo;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.type.MediaType;
import com.whiteape.book.presenter.SearchPresenter;
import com.whiteape.book.ui.adapter.KeyWordAdapter;
import com.whiteape.book.ui.adapter.SearchBookAdapter;
import com.whiteape.book.ui.base.BaseMVPActivity;
import com.whiteape.book.utils.SoftKeyboardUtil;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.URLUtils;
import com.whiteape.book.widget.RefreshLayout;
import com.whiteape.book.widget.TagColor;
import com.whiteape.book.widget.TagGroup;
import com.whiteape.book.widget.itemdecoration.DividerItemDecoration;

import org.angmarch.views.NiceSpinner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import butterknife.BindView;

import static com.whiteape.book.model.type.MediaType.MEDIA_TYPE_ALL;
import static com.whiteape.book.model.type.MediaType.MEDIA_TYPE_COMIC;
import static com.whiteape.book.model.type.MediaType.MEDIA_TYPE_NOVEL;
import static com.whiteape.book.model.type.MediaType.MEDIA_TYPE_VIDEO;


/**
 * Created by newbiechen on 17-4-24.
 */

public class SearchActivity extends BaseMVPActivity<SearchContract.Presenter>
        implements SearchContract.View {
    private static final String TAG = "SearchActivity";
    private static final int TAG_LIMIT = 8;

    @BindView(R.id.search_iv_back)
    ImageView mIvBack;
    @BindView(R.id.search_et_input)
    EditText mEtInput;
    @BindView(R.id.search_iv_delete)
    ImageView mIvDelete;
    @BindView(R.id.search_iv_search)
    ImageView mIvSearch;
    @BindView(R.id.iv_more)
    ImageView mIvMore;
    @BindView(R.id.search_book_tv_refresh_hot)
    TextView mTvRefreshHot;
    @BindView(R.id.search_tg_hot)
    TagGroup mTgHot;
    @BindView(R.id.ll_search_filter)
    LinearLayout mLlSearchFilter;
    @BindView(R.id.tv_search_filter)
    TextView mTvSearchFilter;
    @BindView(R.id.tv_search_progress)
    TextView mTvSearchProgress;
    /*    @BindView(R.id.search_rv_history)
        RecyclerView mRvHistory;*/
    @BindView(R.id.refresh_layout)
    RefreshLayout mRlRefresh;
    @BindView(R.id.refresh_rv_content)
    RecyclerView mRvSearch;

    @BindView(R.id.lvSearchHistory)
    ListView mLvSearchHistory;

    @BindView(R.id.tvClear)
    TextView mTvClearHistory;

    boolean hasInitSearchKey = false;


//    @BindView(R.id.spinner_search_filter)
//    NiceSpinner mSpinnerFilter;

    private KeyWordAdapter mKeyWordAdapter;
    private SearchBookAdapter mSearchAdapter;

    private boolean isTag;
    private List<String> mHotTagList = new ArrayList<>();
    private int mTagStart = 0;
    private String mCurrentSearchKey;
    private int usedSourceCount = 0;
    private int finishedSourceCount = 0;
    AtomicInteger finishedSourceCount2 = new AtomicInteger(0);
    Lock lock = new ReentrantLock();
    private final String FILTER_SEARCH_ALL   = "搜索全部";
    private final String FILTER_SEARCH_COMIC = "仅搜漫画";
    private final String FILTER_SEARCH_VIDEO = "仅搜视频";
    private final String FILTER_SEARCH_NOVEL = "仅搜小说";
    private int filteredMediaType = MEDIA_TYPE_ALL;
    public static final String INPUT_EXTRA_MEDIA_TYPE = "input_media_type";
    private boolean searchExact = ReadSettingManager.getInstance().getSearchOptionsExact();
    private List<String> searchHistoryList;
    private ArrayAdapter<String> searchHistoryAdapter;
    @Override
    protected int getContentId() {
        return R.layout.activity_search;
    }

    @Override
    protected SearchContract.Presenter bindPresenter() {
        return new SearchPresenter();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        if (savedInstanceState!= null && savedInstanceState.containsKey(INPUT_EXTRA_MEDIA_TYPE)) {
            filteredMediaType = savedInstanceState.getInt(INPUT_EXTRA_MEDIA_TYPE);
        } else {
            filteredMediaType = getIntent().getIntExtra(INPUT_EXTRA_MEDIA_TYPE, MEDIA_TYPE_ALL);
        }
        searchHistoryList = ReadSettingManager.getInstance().getSearchHistory();
    }

    private void initSearchHistory(){
        searchHistoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, searchHistoryList);
        mLvSearchHistory.setAdapter(searchHistoryAdapter);
    }

    @Override
    protected void initView() {
        super.initView();
        setUpAdapter();
        initSearchHistory();
        mRlRefresh.setBackground(ContextCompat.getDrawable(this, R.color.white));
        mRlRefresh.setEmptyText("无结果，尝试多导入一些网源试试吧~");
        mTvSearchFilter.setText(MediaType.getName(filteredMediaType));
//        if (filteredMediaType == MEDIA_TYPE_COMIC) {
////            mTvSearchFilter.setText();
////            mSpinnerFilter.attachDataSource(new LinkedList<>(Arrays.asList(FILTER_SEARCH_COMIC, FILTER_SEARCH_NOVEL, FILTER_SEARCH_ALL)));
//        } else if (filteredMediaType == MEDIA_TYPE_NOVEL) {
////            mSpinnerFilter.attachDataSource(new LinkedList<>(Arrays.asList(FILTER_SEARCH_NOVEL, FILTER_SEARCH_COMIC, FILTER_SEARCH_ALL)));
//        } else {
////            mSpinnerFilter.attachDataSource(new LinkedList<>(Arrays.asList(FILTER_SEARCH_ALL, FILTER_SEARCH_NOVEL, FILTER_SEARCH_COMIC)));
//        }
    }


    public int getMediaType(String name) {
        if (name.equals(FILTER_SEARCH_NOVEL)) {
            return MEDIA_TYPE_NOVEL;
        } else if (name.equals(FILTER_SEARCH_COMIC)) {
            return MEDIA_TYPE_COMIC;
        } else if (name.equals(FILTER_SEARCH_VIDEO)) {
            return MEDIA_TYPE_VIDEO;
        } else {
            return MEDIA_TYPE_ALL;
        }
    }

    private void setUpAdapter() {
        mKeyWordAdapter = new KeyWordAdapter();
        mSearchAdapter = new SearchBookAdapter();

        mRvSearch.setLayoutManager(new LinearLayoutManager(this));
        mRvSearch.addItemDecoration(new DividerItemDecoration(this));
    }

    @Override
    protected void initEvent() {
        super.initEvent();

        mTvClearHistory.setOnClickListener( v -> {
            searchHistoryList.clear();
            searchHistoryAdapter.notifyDataSetChanged();
            ReadSettingManager.getInstance().setSearchHistory("");
        });
        mLvSearchHistory.setOnItemClickListener((parent, view, position, id) -> {

            isTag = true;
            mEtInput.setText(searchHistoryList.get(position));
        });
        //退出
        mIvBack.setOnClickListener(
                (v) -> onBackPressed()
        );

        //输入框
        mEtInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().equals("")) {
                    //隐藏delete按钮和关键字显示内容
                    stopSearching();
                    if (mIvDelete.getVisibility() == View.VISIBLE) {
                        mIvDelete.setVisibility(View.INVISIBLE);
                        mRlRefresh.setVisibility(View.INVISIBLE);
                        //删除全部视图
                        mKeyWordAdapter.clear();
                        mSearchAdapter.clear();
                        mRvSearch.removeAllViews();
                    }
                    return;
                }
                //显示delete按钮
                if (mIvDelete.getVisibility() == View.INVISIBLE) {
                    mIvDelete.setVisibility(View.VISIBLE);
                    mRlRefresh.setVisibility(View.VISIBLE);
                    //默认是显示完成状态
                    mRlRefresh.showFinish();
                }
                //搜索
                String query = s.toString().trim();
                mCurrentSearchKey = query;
                if (isTag) {
                    mRlRefresh.showLoading();
                    finishedSourceCount2.set(0);
                    mPresenter.searchBook(query, filteredMediaType);

                    isTag = false;
                    updateHistory(query);
                } else {
                    //传递
                    mPresenter.searchKeyWord(query);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //键盘的搜索
        mEtInput.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //修改回车键功能
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    searchBook();
                    return true;
                }
                return false;
            }
        });

        //进行搜索
        mIvSearch.setOnClickListener(
                (v) -> searchBook()
        );

        mIvMore.setOnClickListener(v -> {
            showSearchOptions();
        });

        //删除字
        mIvDelete.setOnClickListener(
                (v) -> {
                    mEtInput.setText("");
                    toggleKeyboard();
                }
        );

        //点击查书
        mKeyWordAdapter.setOnItemClickListener(
                (view, pos) -> {
                    //显示正在加载
                    mRlRefresh.showLoading();
                    String book = mKeyWordAdapter.getItem(pos);

                    isTag = true;
                    mEtInput.setText(book);
//                    mPresenter.searchBook(book, filteredMediaType);
//                    toggleKeyboard();
                    hideKeyboard();
                }
        );

        //Tag的点击事件
        mTgHot.setOnTagClickListener(
                tag -> {
                    isTag = true;
                    mEtInput.setText(tag);

                }
        );

        //Tag的刷新事件
        mTvRefreshHot.setOnClickListener(
                (v) -> refreshTag()
        );

        //书本的点击事件
        mSearchAdapter.setOnItemClickListener(
                (view, pos) -> {
                    stopSearching();

                    CollectionMediaBean collectionMediaBean = new CollectionMediaBean();
                    SearchResultBo resultBean = mSearchAdapter.getItem(pos);


                    collectionMediaBean.setMediaType(resultBean.getMediaType());
                    collectionMediaBean.setAuthor(resultBean.getAuthor());
                    collectionMediaBean.setCoverUrl(resultBean.getCoverUrl());
                    collectionMediaBean.setId(resultBean.getDetailUrl());
                    collectionMediaBean.setCategory(resultBean.getCategory());
                    collectionMediaBean.setDesc(resultBean.getDesc());
                    collectionMediaBean.setLastChapter(resultBean.getLastChapter());
                    collectionMediaBean.setLastUpdated(resultBean.getLastUpdated());
                    collectionMediaBean.setState(resultBean.getState());
                    collectionMediaBean.setTitle(resultBean.getTitle());
                    collectionMediaBean.setWordCount(resultBean.getWordCount());
                    collectionMediaBean.setSiteSourceBean(resultBean.getSiteSourceBean());
                    collectionMediaBean.setVarMap(resultBean.getVarMap());
//                    collectionMediaBean.setBookSourceUrl();
//                    String bookId = mSearchAdapter.getItem(pos).get_id();
                    MediaDetailActivity.startActivity(this, collectionMediaBean, null);
//                    BookReadActivity.startActivity(SearchActivity.this, );
                }
        );

//        mSpinnerFilter.setOnSpinnerItemSelectedListener((parent, view, position, id) -> {
//            filteredMediaType = getMediaType((String)parent.getItemAtPosition(position));
//        });
        mLlSearchFilter.setOnClickListener(v -> {
            String[] choices = new String[]{FILTER_SEARCH_NOVEL, FILTER_SEARCH_COMIC, FILTER_SEARCH_ALL};
            new AlertDialog.Builder(this)
                    .setTitle(R.string.search_filter)
                    .setItems(choices, ((dialog, which) -> {
                        filteredMediaType = getMediaType(choices[which]);
                        mTvSearchFilter.setText(MediaType.getName(filteredMediaType));
                    })).show();
        });
    }

    private void showSearchOptions(){
//        boolean exact = ReadSettingManager.getInstance().getSearchOptionsExact();
        boolean[] checked = null;
        if(searchExact){
            checked = new boolean[]{true};
        }
        new AlertDialog.Builder(this)
                .setTitle("搜索选项")
                .setMultiChoiceItems(new String[]{"精准搜索"},checked, (dialog, which, isChecked) -> {
                    if(which == 0){
                        ReadSettingManager.getInstance().setSearchOptionsExact(isChecked);
                        searchExact = isChecked;
                    }

                })
                .setPositiveButton("确定",((dialog, which) -> {

                }))
                .show();

    }

    private void updateHistory(String query){

        ReadSettingManager.getInstance().addSearchHistory(query);
        searchHistoryList.clear();
        searchHistoryList.addAll(ReadSettingManager.getInstance().getSearchHistory());
        searchHistoryAdapter.notifyDataSetChanged();
    }

    private void searchBook() {
        String query = mEtInput.getText().toString().trim();
        if (!query.equals("")) {
            mCurrentSearchKey = query;
            mSearchAdapter.clear();
            mRlRefresh.setVisibility(View.VISIBLE);
            mRlRefresh.showLoading();
            finishedSourceCount2.set(0);
            mPresenter.searchBook(query, filteredMediaType);
            //显示正在加载
            mRlRefresh.showLoading();



//            toggleKeyboard();
            hideKeyboard();
            updateHistory(query);
        }
    }

    private void hideKeyboard() {

        mEtInput.clearFocus();
        SoftKeyboardUtil.hideKeyboard(mEtInput);
    }

    private void toggleKeyboard() {

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @Override
    protected void startLogic() {
        super.startLogic();
        //默认隐藏
        mRlRefresh.setVisibility(View.GONE);

        String initSearchKey = getIntent().getStringExtra("searchKey");
        if (!StringUtils.isEmpty(initSearchKey)) {
            hasInitSearchKey = true;
            mEtInput.setText(initSearchKey);
            searchBook();
        }
        //获取热词
        mPresenter.searchHotWord();
    }

    @Override
    public void showError() {
    }

    @Override
    public void complete() {

    }

    @Override
    public void finishHotWords(List<String> hotWords) {
        if(isDestroyed() || isFinishing()){
            return;
        }
        mHotTagList = hotWords;
        refreshTag();
    }


    private void refreshTag() {
        if (mHotTagList.size() == 0) {
            //TODO 多次点击问题
            mPresenter.searchHotWord();
            return;
        }
        if (mHotTagList.size() <= TAG_LIMIT) {
            return;
        }
        int last = mTagStart + TAG_LIMIT;
        if (mHotTagList.size() <= last) {
//            mTagStart = 0;
            last = mHotTagList.size();
            List<String> tags = mHotTagList.subList(mTagStart, last);

            List<TagColor> colors = TagColor.getRandomColors(tags.size());
            String[] tagsArr = new String[tags.size()];
            mTgHot.setTags(colors, tags.toArray(tagsArr));
            mTagStart = 0;
            return;
        }
        List<String> tags = mHotTagList.subList(mTagStart, last);
        List<TagColor> colors = TagColor.getRandomColors(tags.size());
        String[] tagsArr = new String[tags.size()];
        mTgHot.setTags(colors, tags.toArray(tagsArr));
        mTagStart += TAG_LIMIT;
    }

    @Override
    public void finishKeyWords(List<String> keyWords) {
        if (keyWords.size() == 0) mRlRefresh.setVisibility(View.INVISIBLE);
        mKeyWordAdapter.refreshItems(keyWords);
        if (!(mRvSearch.getAdapter() instanceof KeyWordAdapter)) {
            mRvSearch.setAdapter(mKeyWordAdapter);
        }
    }

    @Override
    public void finishBooks(List<SearchResultBo> searchResultBos) {
//        lock.lock();
//        try {
//            finishedSourceCount++;
//            updateSearchProgress();
//        }finally {
//            lock.unlock();
//        }
        finishedSourceCount2.getAndIncrement();
        updateSearchProgress();
        if (searchResultBos == null || searchResultBos.isEmpty()) {
            if (finishedSourceCount >= usedSourceCount && mSearchAdapter.getItemSize() == 0) {
                mRlRefresh.showEmpty();
            }
            return;
        }
        //已经改变了media type还是有上一个的搜索结果回来
        if(filteredMediaType != MEDIA_TYPE_ALL && searchResultBos.get(0).getMediaType() != filteredMediaType){
            return;
        }
//        searchResultBos.get(0).getSiteSourceBean().getSiteHostUrl();
        for (SearchResultBo searchResultBo : mSearchAdapter.getItems()) {
            if (searchResultBo.getSiteSourceBean().getSiteHostUrl().equals(searchResultBos.get(0).getSiteSourceBean().getSiteHostUrl())) {
                //表示已经有这个网源的请求数据了，这个是重复数据
                return;
            }

        }

        //按照 标题+作者 来区分一个作品，然后这个作品，可以累加多个源
        int beforeSize = mSearchAdapter.getItemCount();
        for (SearchResultBo resultBo : searchResultBos) {
            if (resultBo.getTitle().trim().equals(mCurrentSearchKey)) {
                boolean hasUpdated = false;
                for (int i = 0; i < mSearchAdapter.getItemCount(); i++) {
                    SearchResultBo adapterData = mSearchAdapter.getItem(i);
                    if (!adapterData.getTitle().equals(mCurrentSearchKey)) {
                        break;
                    }
                    //相同类型（小说、漫画）而且作者相同的
                    if (adapterData.getSiteSourceBean().getSiteType() == resultBo.getSiteSourceBean().getSiteType() &&
                            adapterData.getAuthor().equals(resultBo.getAuthor())) {
                        if (StringUtils.isEmpty(adapterData.getCoverUrl()) && !StringUtils.isEmpty(resultBo.getCoverUrl())) {
                            adapterData.setCoverUrl(URLUtils.getAbsolutePath(resultBo.getSiteSourceBean().getSiteHostUrl(), resultBo.getCoverUrl()));
                        }
                        if (adapterData.getBackupSiteSourceList() == null) {
                            adapterData.setBackupSiteSourceList(new ArrayList<>());
                        }
                        adapterData.getBackupSiteSourceList().add(resultBo.getSiteSourceBean());
                        hasUpdated = true;
                        mSearchAdapter.notifyItemChanged(i);
                    }
                }
                if (!hasUpdated) {
                    mSearchAdapter.addItem(0, resultBo);
                }

                //精准搜索匹配作者
            } else if(!searchExact || resultBo.getTitle().trim().contains(mCurrentSearchKey) || resultBo.getAuthor().trim().contains(mCurrentSearchKey)){
                mSearchAdapter.addItem(resultBo);
            }
        }
        mSearchAdapter.notifyItemRangeChanged(beforeSize, mSearchAdapter.getItemCount() - beforeSize);

        if(mSearchAdapter.getItemSize() > 0){
            mRlRefresh.showFinish();
        }
//        if ( mSearchAdapter.getItemSize() == 0) {
////            mRlRefresh.showEmpty();
//            mRlRefresh.showFinish();
//        } else {
//            //显示完成
//            mRlRefresh.showFinish();
//        }
        //加载
        if (!(mRvSearch.getAdapter() instanceof SearchBookAdapter)) {
            mRvSearch.setAdapter(mSearchAdapter);
        }


    }

    @Override
    public void errorNums(int num) {
//        mRlRefresh.showEmpty();
//        lock.lock();
//        try {
//            finishedSourceCount++;
//            updateSearchProgress();
//        }finally {
//            lock.unlock();
//        }
        finishedSourceCount2.getAndAdd(num);
        updateSearchProgress();
        if (finishedSourceCount >= usedSourceCount && mSearchAdapter.getItemSize() == 0) {
            mRlRefresh.showEmpty();
        }
    }

    @Override
    public void onBackPressed() {
        if (mRlRefresh.getVisibility() == View.VISIBLE && !hasInitSearchKey) {
            mEtInput.setText("");
//            mPresenter.detachView();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void setUsedSourceCount(int count) {
        finishedSourceCount = 0;
        usedSourceCount = count;
        updateSearchProgress();
    }

    private void updateSearchProgress(){
        mTvSearchProgress.setText("搜索中(" + finishedSourceCount2.get() + "/" + usedSourceCount+")");
    }

    private void stopSearching(){
        mTvSearchProgress.setText("搜索停止");
        if(mPresenter != null){
            mPresenter.stopSearching();
        }

    }
}
